package com.oracle.controller;

import com.oracle.annotation.Action;
import com.oracle.annotation.ActionType;
import com.oracle.news.service.api.NewsCategoryServiceApi;
import com.oracle.news.service.api.NewsServiceApi;
import com.oracle.pojo.Category;
import com.oracle.pojo.News;
import com.oracle.utils.FastDFSClient;
import com.oracle.vo.NewsSearch;
import com.oracle.vo.PageVo;
import com.oracle.vo.ResultEntity;
import com.oracle.vo.SearchVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.MapsId;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/admin/news")
public class NewsController {

    @Autowired(required = false)
    private NewsCategoryServiceApi newsCategoryServiceApi;
    @Autowired(required = false)
    private NewsServiceApi newsServiceApi;
    @Value("${upload_path_address}")
    private String fileUploadAddress;

    @Action(ActionType.PAGE_JUMPS)
    @RequestMapping("/addview")
    public String newsAddView(Model model){
        //获取新闻二级类型
        ResultEntity<List<Category>> resultEntity = this.newsCategoryServiceApi.getNewsCategoryAll();
        List<Category> categoryList = resultEntity.getData();
        categoryList = categoryList.stream().filter(category -> category.getParent()!=0).collect(Collectors.toList());
        model.addAttribute("categoryList",categoryList);
        return "admin/news/addview";
    }

    /*
     * 1、文件上传时的服务器地址（写一个properties文件），fastDFS的配置文件（文件追踪服务的地址）
     * 2、当文件上传后，返回的文件信息，不包含服务器的地址，需要在配置文件中额外的指定
     * 3、文件存储的位置，不包含服务器的地址（文件存储位置 + 文件名称）
     * 4、记录文件上传后的服务器地址，用于图片回显
     * 5、富文本编辑器中有图片上传，它可以把图片回显，我们需要把上传和回显的位置进行更改：自己重写实现富文本编辑器内的图片上传实现
     *
     */
    @Action(ActionType.ADD)
    @RequestMapping("/add")
    public String newsAdd(News news) {
        ResultEntity resultEntity = this.newsServiceApi.addNews(news);
        System.out.println(news);
        return "admin/comm/success";
    }

    @RequestMapping("/upload")
    @ResponseBody
    public Map uploadNewsImage(MultipartFile newsImage){
        //获取文件真实名称
        String originalFilename = newsImage.getOriginalFilename();
        //获取后坠
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
        String fileId = null;
        try {
            FastDFSClient fastDFSClient = new FastDFSClient("classpath:conf/fdfs_client.conf");
            fileId = fastDFSClient.uploadFile(newsImage.getBytes(), suffix);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //fileId 组名+路径+随机id名称
        String url = fileUploadAddress + fileId;
        Map maps = new HashMap();
        maps.put("imageSrc",url);
        return maps;
    }


    @RequestMapping("/editUpload")
    @ResponseBody
    public Map editUpload(MultipartFile imgFile){
        //获取文件真实名称
        String originalFilename = imgFile.getOriginalFilename();
        //获取后坠
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
        String fileId = null;
        Map maps = new HashMap();
        try {
            FastDFSClient fastDFSClient = new FastDFSClient("classpath:conf/fdfs_client.conf");
            fileId = fastDFSClient.uploadFile(imgFile.getBytes(), suffix);
            //fileId 组名+路径+随机id名称
            String url = fileUploadAddress + fileId;
            maps.put("error",0);
            maps.put("url",url);
        } catch (Exception e) {
            maps.put("error",1);
            e.printStackTrace();
        }
        return maps;
    }


    @Action(ActionType.QUERY)
    @RequestMapping("/list")
    public String listView(@RequestParam(value = "currentPage",required = false,defaultValue = "1")Integer pageIndex,
                           @RequestParam(value = "pageSize",required = false,defaultValue = "10")Integer pageSize,
                           SearchVO sv, Model model){
        ResultEntity<List<Category>> resultEntity = this.newsCategoryServiceApi.getNewsCategoryAll();
        List<Category> categoryList = resultEntity.getData();
        categoryList = categoryList.stream().filter(category -> category.getParent()!=0).collect(Collectors.toList());
        model.addAttribute("categoryList",categoryList);
        NewsSearch ns = null;
        if (sv!=null){
            ns = new NewsSearch();
            ns.setAuthor(sv.getAuthor());
            ns.setCategory(sv.getCategory());
            ns.setMaxTime(sv.getMaxTime());
            ns.setMinTime(sv.getMinTime());
            ns.setTitle(sv.getTitle());
            if (sv.getStatus()!=null && sv.getStatus()!=-1){
                ns.setStatus(sv.getStatus());
            }
        }

        PageVo<News> pv = this.newsServiceApi.getNewsBySearch(pageIndex, pageSize, ns==null?new NewsSearch():ns);
        model.addAttribute("pv",pv);
        model.addAttribute("sv",sv);
        System.out.println(pv.getObjList().size());
        return "admin/news/list";
    }

    @Action(ActionType.PAGE_JUMPS)
    @RequestMapping("/editview")
    public String newsEditView(Integer id,Model model){
        //获取新闻二级类型
        ResultEntity<List<Category>> resultEntity = this.newsCategoryServiceApi.getNewsCategoryAll();
        List<Category> categoryList = resultEntity.getData();
        categoryList = categoryList.stream().filter(category -> category.getParent()!=0).collect(Collectors.toList());
        model.addAttribute("categoryList",categoryList);
        ResultEntity<News> newsResultEntity = this.newsServiceApi.getNewsInfoById(id);
        model.addAttribute("news",newsResultEntity.getData());
        return "admin/news/editview";
    }

    @Action(ActionType.UPDATE)
    @RequestMapping("/edit")
    public String newsEdit(News news){
        ResultEntity resultEntity = this.newsServiceApi.updateNews(news);
        return "admin/comm/success";
    }

    @Action(ActionType.DELETE)
    @RequestMapping("/delete")
    @ResponseBody
    public Map newsDelete(Integer id,Integer istop){
        Map<String,Object> maps = new HashMap<String, Object>();
        ResultEntity resultEntity = this.newsServiceApi.deleteNews(id,istop);
        maps.put("code",resultEntity.getCode());
        maps.put("msg",resultEntity.getMsg());
        return maps;
    }


}
